import dayjs from "dayjs"
import schema from 'validate'
const repairValidate = new schema({
  houseId: {
    required: true,
    message: '报修房屋不能为空'
  },
  repairItemId: {
    required: true,
    message: '维修项目不能为空'
  },
  mobile: {
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不正确'
  },
  appointment: {
    required: true,
    message: '预约日期不能为空'
  },
  description: {
    required: true,
    match: /^.{1,200}$/,
    message: '描述信息为1~200字'
  },
  attachment: {
    type: Array,
    length: { min: 0, max: 9 },
    message: '附件信息为 0~9 个'
  }
}, { strip: false })

Page({
  data: {
    currentDate: new Date().getTime(),
    houseLayerVisible: false,
    repairLayerVisible: false,
    dateLayerVisible: false,
    /** 房屋列表 */
    houseList: [],
    /** 报修房屋 id */
    houseId: '',
    /** 报修房屋 name */
    houseInfo: '',
    /** 维修项目 */
    repairItem: [],
    /** 维修项目 id */
    repairItemId: '',
    /** 维修项目 name */
    repairItemName: '',
    /** 手机号码 */
    mobile: '',
    /** 预约日期 */
    appointment: '',
    /** 问题描述-做多200字 */
    description: '',
    /** 附件信息，0-9个 */
    attachment: [
      // { url: '/repair_pkg/static/uploads/attachment.jpg' },
      // { url: '/repair_pkg/static/uploads/attachment.jpg' },
    ]
  },

  async onLoad(ev) {
    // console.log(ev.id);
    if (ev.id) {
      this.setData({ id: ev.id })
      wx.setNavigationBarTitle({ title: '修改报修信息' })
      /** 数据回流 */
      let res = await wx.http({
        url: '/repair/' + this.data.id
      })
      /** name 格式转换 */
      res.data.houseInfo = res.data.houseInfo.replace(/(\d)(\d+)/, '$1号楼 $2室')
      this.setData(res.data)
    } else {
      wx.setNavigationBarTitle({ title: '填写报修信息' })
    }
    this.getHouseList()
    this.getRepairItem()
  },

  /** 房屋列表信息 */
  async getHouseList() {
    let res = await wx.http({
      url: '/house',
    })

    /** name 格式转换 */
    let houseList = res.data.map((item) => {
      let name = item.name.replace(/(\d)(\d+)/, '$1号楼 $2室')
      return { id: item.id, name }
    })
    this.setData({
      houseList
    })
  },

  /** 获取维修项目 */
  async getRepairItem() {
    let res = await wx.http({
      url: '/repairItem',
    })

    this.setData({
      repairItem: res.data
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openRepairLayer() {
    this.setData({ repairLayerVisible: true })
  },
  closeRepairLayer() {
    this.setData({
      repairLayerVisible: false,
    })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  /** 选择房屋 */
  selectHouse(ev) {
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name
    })
  },

  /** 选择维修项目 */
  selectRepairItem(ev) {
    // console.log(ev);
    this.setData({
      repairItemId: ev.detail.id,
      repairItemName: ev.detail.name
    })
  },

  /** 选择预约日期 */
  appointmentConfirm(ev) {
    // console.log(ev);
    let appointment = dayjs(ev.detail).format('YYYY-MM-DD')
    // console.log(appointment);
    this.setData({
      appointment,
      dateLayerVisible: false
    })
  },

  /** 附件上传 */
  attachmentUpload(ev) {
    let tempURL = ev.detail.file.url

    let token = getApp().token
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: tempURL,
      name: 'file',
      header: {
        Authorization: `Bearer ${token}`
      },
      success: (attachmentRes) => {
        if (attachmentRes.statusCode === 401) {
          wx.utils.toast(attachmentRes.data.message)
          wx.navigateTo({
            url: '/pages/login/index'
          })
        }
        let data = JSON.parse(attachmentRes.data)
        let attachment = this.data.attachment
        attachment.push(data.data)
        this.setData({ attachment })
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  /** 删除附件信息 */
  deleteAttachment(ev) {
    wx.showModal({
      title: '提示',
      content: '您确定要删除吗？',
      success: (res) => {
        if (res.confirm) {
          let attachment = this.data.attachment
          attachment.splice(ev.detail.index, 1)
          this.setData({
            attachment
          })
        }
      }
    })
  },

  /** 提交报修 */
  async submit() {
    const { id, houseId, repairItemId, mobile, appointment, description, attachment } = this.data
    /** 报修参数 */
    let params = {}
    if (id) {
      params = { id, houseId, repairItemId, mobile, appointment, description, attachment }
    } else {
      params = { houseId, repairItemId, mobile, appointment, description, attachment }
    }
    /** 表单校验 */
    const errors = repairValidate.validate(params)
    if (errors.length !== 0) {
      // console.log(errors[0].message);
      return wx.utils.toast(errors[0].message)
    }

    let res = await wx.http({
      url: '/repair',
      method: 'post',
      data: params
    })
    // console.log(res);

    if (res.code !== 10000) {
      return wx.utils.toast(res.message)
      // console.log(res.data.id);
    }

    wx.showToast({
      title: '提交报修成功'
    })

    setTimeout(() => {
      wx.reLaunch({
        url: '/repair_pkg/pages/list/index',
      })
    }, 1500)
  },
})

